package org.example.producer.exception;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.example.common.enumerate.ResponseCode;
import org.example.common.model.vo.base.ResponseVO;
import org.example.common.util.ResponseUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author lsliang
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value =Exception.class)
    public ResponseVO exceptionHandler(Exception e) {
        log.error(e.getMessage());
        return ResponseUtils.error(ResponseCode.UNKNOWN_EXCEPTION);
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResponseVO<String> handleConstraintViolationException(BindException bindException) {
        Map<String, List<String>> errorMap = Maps.newHashMap();
        bindException.getAllErrors().forEach(item -> {
            Object[] arguments = item.getArguments();
            if (ArrayUtil.isNotEmpty(arguments) && arguments[0] instanceof DefaultMessageSourceResolvable) {
                 String field = ((DefaultMessageSourceResolvable)arguments[0]).getCodes()[1];
                 List<String> errorList = errorMap.get(field) == null ? Lists.newArrayList() : errorMap.get(field);
                 errorList.add(item.getDefaultMessage());
                 errorMap.put(field, errorList);
            } else {
                log.error("未能提取到参数校验错误信息---{0}", item.toString());
            }
        });
        log.error(errorMap.toString());
        return ResponseUtils.error(errorMap);
    }
}
